package com.chenjun.web.controller.activiti;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.json.Json;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModelUnPaginationInterceptor;
import com.chenjun.common.util.DateJsonValueProcessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/process/model")
public class ModelController {

	@Resource
	private RepositoryService repositoryService;
	
	/**
	 * 页面展示
	 * 
	 * @return ModelAndView
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("activiti/process/model/list");
		return mv;
	}
	
	/**
	 * 分页查询流程模型
	 * @param datagrid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/search")
	public void getDeployPage(DataGridModelUnPaginationInterceptor datagrid, HttpServletResponse response) throws Exception{
		int rows = datagrid.getRows();
		int page = datagrid.getPage();
		int start = datagrid.getStart();
		Map<String, Object> params = datagrid.getParams();
		String modelName = params.isEmpty() ? "" : params.get("modelName").toString();
		
		ResultDto rtDto = new ResultDto();
		//当前页
		int pageNo = start / rows;
		//取得总数量
		long modelCount = repositoryService.createModelQuery().modelNameLike("%"+modelName+"%").count();
		
		List<Model> modelList=repositoryService.createModelQuery()//创建流程查询实例
				.orderByCreateTime().desc()  //降序
				.modelNameLike("%"+modelName+"%")   //根据Name模糊查询
				.listPage(pageNo, rows);
		
		Pagination data = new Pagination();
		data.setAaData(modelList);
		data.setiTotalDisplayRecords((int)modelCount);
		data.setiTotalLongRecords(modelCount);
		data.setiTotalRecords((int)modelCount);
		data.setsEcho(page);
		rtDto.setData(data);
		
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.setExcludes(new String[]{"resources"});
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
		JSONObject result= JSONObject.fromObject(rtDto, jsonConfig);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(result.toString());
		out.flush();
		out.close();
	}
	
	/** 
     * 根据Model部署流程 
     */  
    @ResponseBody  
    @RequestMapping("/deploy/{id}")  
    public ResultDto deploy(@PathVariable String id) {  
    	ResultDto rtDto = new ResultDto();
        try {  
            Model modelData = repositoryService.getModel(id);  
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));  
            byte[] bpmnBytes = null;  
  
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);  
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);  
  
            String processName = modelData.getName() + ".bpmn20.xml";  
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
            rtDto.setData("部署成功，部署ID=" + deployment.getId());
        } catch (Exception e) {  
        	rtDto.resultError();
			rtDto.setMessage("模型部署流程失败");
        }  
        return rtDto;  
    }  
	
	/**
	 * 删除流程模型
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public ResultDto delDeploy(@PathVariable String id) throws Exception{
		ResultDto rtDto = new ResultDto();
		repositoryService.deleteModel(id);
		return rtDto;
	}
	
}
